package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.exception.AddressBookBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     *  新增地址
     * @param addressBook
     */
    @Override
    public void add(AddressBook addressBook) {
        // 保存到数据库
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.insert(addressBook);
    }

    /**
     *  查询地址
     * @return
     */
    @Override
    public List<AddressBook> list() {
        return addressBookMapper.getAll(BaseContext.getCurrentId());
    }

    /**
     *  设置默认地址
     * @param addressBook
     */
    @Transactional
    @Override
    public void setDefault(AddressBook addressBook) {
        //将当前用户的所有地址设置非默认
        addressBookMapper.getAll(BaseContext.getCurrentId()).forEach(item -> {
            item.setIsDefault(0);
            addressBookMapper.update(item);
        });
        //设置当前地址为默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }

    /**
     *  根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    /**
     *  修改地址
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     *  查询默认地址
     * @return
     */
    @Override
    public AddressBook getDefault() {
        //判断当前用户是否有地址
        List<AddressBook> addressBooks = addressBookMapper.getAll(BaseContext.getCurrentId());
        if (CollectionUtils.isEmpty(addressBooks)){
           throw  new AddressBookBusinessException(MessageConstant.DEFAULT_ADDRESS_NOT_EXIST);
        }
        //判断当前用户是否有默认地址
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .isDefault(1)
                .build();
        AddressBook defaultAddress = addressBookMapper.getDefault(addressBook);
        if (defaultAddress == null){
            throw new AddressBookBusinessException(MessageConstant.DEFAULT_ADDRESS_NOT_EXIST);
        }
        return defaultAddress;
    }

    /**
     *  删除地址
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }
}
